package pl.perseus.service.user;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import pl.perseus.dao.IUserDao;
import pl.perseus.model.User;

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;

@Service("userDetailsService") 
public class UserDetailsServiceImpl implements UserDetailsService {

  @Autowired private IUserDao dao;
  @Autowired private Assembler assembler;

  @Transactional(readOnly = true)
  public UserDetails loadUserByUsername(String login) throws UsernameNotFoundException, DataAccessException {
	Logger.getLogger(UserDetailsServiceImpl.class).log(Level.INFO, "User: " + login + " logs in to the system. " + Calendar.getInstance().getTime());
    User userEntity = dao.selectByLoginUser(login);
    if (userEntity == null)
      throw new UsernameNotFoundException("user not found");
    return assembler.buildUserFromUserEntity(userEntity);
  }
}
